package com.wwl.cms.config.elasticsearch;

import com.google.gson.*;
import com.wwl.cms.dto.AuditPoiVo;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @author wwl
 * @version 1.0
 * @date 2021/11/29 16:41
 * @description:
 */
public class CommonQueryUtils {
    /**
     * 处理ES返回的数据，封装
     */
    public static List<AuditPoiVo> parseResponse(SearchResponse searchResponse) {
        GsonBuilder builder = new GsonBuilder();
        // Register an adapter to manage the date types as long values
        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                return new Date(json.getAsJsonPrimitive().getAsLong());
            }
        });
        Gson gson = builder.create();
        List<AuditPoiVo> list = new LinkedList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            // 用gson直接解析
            AuditPoiVo auditPoiVo = gson.fromJson(hit.getSourceAsString(), AuditPoiVo.class);
            list.add(auditPoiVo);
        }
        return list;
    }
}
